<template>
  <div class="carts">
    <header class="header">
      <div class="top-nav">
        <div class="nav-container">
          <div class="logo">
            <img src="/public/logo.png" alt="宠物商城" />
          </div>
          <router-link to="/" class="nav-item">首页</router-link>
          <router-link to="/type" class="nav-item">商品分类</router-link>
          <router-link to="/carts" class="nav-item active">购物车</router-link>
          <router-link to="/personal-center" class="nav-item">个人中心</router-link>
        </div>
      </div>
      <div class="call">
        <router-link to="/service" class="call-item"><img src="../meall/me-img/call.png" alt="" class="call-img" />客服</router-link>
      </div>
    </header>

    <div class="main-content">
      <div class="container">
        <div class="cart-container" v-if="cartItems.length > 0">
          <!-- 原有购物车内容 -->
          <div class="cart-header">
            <div></div>
            <div class="header-item header-product">商品信息</div>
            <div class="header-item">单价</div>
            <div class="header-item">数量</div>
            <div class="header-item">小计</div>
            <div class="header-item">操作</div>
          </div>
          <div class="cart-items">
            <div v-for="item in cartItems" :key="item.product_id" class="cart-item">
              <div class="item-checkbox">
                <input type="checkbox" v-model="item.selected" @change="updateSelectAll" class="item-select-checkbox" />
              </div>
              <div></div>
              <div class="item-info">
                <img :src="item.image_url" :alt="item.name" class="item-image" />
                <div>
                  <div class="item-name">{{ item.name }}</div>
                  <div v-if="item.quantity > item.stock_quantity" class="stock-warning">库存不足，仅剩{{ item.stock_quantity }}件</div>
                </div>
              </div>
              <div class="item-price">{{ item.price.toFixed(2) }}</div>
              <div class="item-quantity">
                <div class="quantity-control">
                  <button
                    @click="updateQuantity(item, -1)"
                    class="quantity-btn minus-btn"
                    :disabled="item.quantity <= 1"
                    :class="{ 'disabled-btn': item.quantity <= 1 }"
                  >
                    -
                  </button>
                  <input type="text" class="quantity-input" :value="item.quantity" readonly />
                  <button
                    @click="updateQuantity(item, 1)"
                    class="quantity-btn plus-btn"
                    :disabled="item.quantity >= item.stock_quantity"
                    :class="{
                      'disabled-btn': item.quantity >= item.stock_quantity,
                    }"
                  >
                    +
                  </button>
                </div>
              </div>
              <div class="item-subtotal">
                {{ (item.price * item.quantity).toFixed(2) }}
              </div>
              <div class="item-action">
                <button @click="removeItem(item)" class="remove-btn">删除</button>
              </div>
            </div>
            <div v-if="error" class="error">{{ error }}</div>
          </div>
          <div class="cart-footer">
            <div class="footer-left">
              <input type="checkbox" v-model="selectAll" @change="toggleSelectAll" class="select-all-checkbox" />
              <span class="select-all-text">全选</span>
            </div>
            <div class="footer-right">
              <span class="total-info"> 已选{{ selectedQuantity }}件商品，总计: {{ selectedTotalPrice.toFixed(2) }}元 </span>
              <button @click="checkout" class="checkout-btn">去结算</button>
            </div>
          </div>
        </div>

        <!-- 购物车为空时的显示 -->
        <div v-else class="empty-cart">
          <div class="empty-cart-icon">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="80"
              height="80"
              viewBox="0 0 24 24"
              fill="none"
              stroke="#999"
              stroke-width="1.5"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <circle cx="9" cy="21" r="1"></circle>
              <circle cx="20" cy="21" r="1"></circle>
              <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
            </svg>
          </div>
          <h3 class="empty-cart-title">购物车空空如也</h3>
          <p class="empty-cart-desc">快去挑选心仪的商品吧~</p>
          <router-link to="/type" class="empty-cart-button">去逛逛</router-link>
        </div>
      </div>
      <div class="content-down">
        <h2 class="recommend-title">推荐商品</h2>
        <div class="recommend-products">
          <div v-for="product in recommendedProducts" :key="product.product_id" class="product-card">
            <img :src="product.image_url" :alt="product.name" class="product-image" />
            <div class="product-info">
              <h3 class="product-name">{{ product.name }}</h3>
              <p class="product-price">¥{{ product.price.toFixed(2) }}</p>
              <p class="product-stock">库存: {{ product.stock_quantity }}件</p>
              <button @click="addToCart(product)" class="add-to-cart-btn">加入购物车</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Header from "@/components/Header.vue";
import Footer from "@/components/Footer.vue";
import { mapState, mapMutations } from "vuex";

export default {
  name: "CartsView",
  components: {
    Header,
    Footer,
  },
  data() {
    return {
      recommendedProducts: [], // 新增推荐商品数组
      error: null,
      selectAll: false,
      cartItems: [], // 初始化为空数组
    };
  },
  computed: {
    ...mapState(["cartItems"]),
    selectedQuantity() {
      return this.cartItems.filter((item) => item.selected).reduce((sum, item) => sum + item.quantity, 0);
    },
    selectedTotalPrice() {
      return this.cartItems.filter((item) => item.selected).reduce((sum, item) => sum + item.price * item.quantity, 0);
    },
  },
  created() {
    this.fetchCartData();
    this.fetchRecommendedProducts(); // 新增获取推荐商品方法
  },
  methods: {
    ...mapMutations(["removeItem"]),
    updateQuantity(item, change) {
      this.$store.commit("updateQuantity", { product: item, change });
    },
    async fetchCartData() {
      try {
        const response = await fetch("/public/carts.json");
        if (!response.ok) throw new Error("网络响应不正常");
        const data = await response.json();
        // 初始化时所有商品默认不选中
        this.cartItems = data.cart.items.map((item) => ({
          ...item,
          selected: false,
        }));
      } catch (err) {
        this.error = "加载购物车数据失败，请刷新页面重试";
        console.error("加载购物车数据失败:", err);
        // 保持购物车为空
        this.cartItems = [];
      }
    },
    // 新增方法：获取推荐商品
    async fetchRecommendedProducts() {
      try {
        const response = await fetch("/public/product.json");
        if (!response.ok) throw new Error("获取商品数据失败");
        const data = await response.json();

        // 随机选择4个不同的商品
        const allProducts = data.cart.items;
        const shuffled = [...allProducts].sort(() => 0.5 - Math.random());
        this.recommendedProducts = shuffled.slice(0, 4);
      } catch (err) {
        console.error("获取推荐商品失败:", err);
      }
    },
    // 新增方法：添加商品到购物车
    addToCart(product) {
      // 检查是否已经在购物车中
      const existingItem = this.cartItems.find((item) => item.product_id === product.product_id);

      if (existingItem) {
        // 如果已经在购物车中，增加数量（不超过库存）
        if (existingItem.quantity < existingItem.stock_quantity) {
          existingItem.quantity += 1;
          alert(`已增加商品数量，当前数量：${existingItem.quantity}`);
        } else {
          alert(`已达到库存上限，无法继续添加`);
        }
      } else {
        // 如果不在购物车中，添加新商品
        this.cartItems.push({
          ...product,
          quantity: 1,
          selected: false,
        });
        alert("已添加到购物车");
      }
    },
    toggleSelectAll() {
      this.cartItems.forEach((item) => {
        item.selected = this.selectAll;
      });
    },
    updateSelectAll() {
      this.selectAll = this.cartItems.every((item) => item.selected);
    },
    updateQuantity(item, change) {
      const newQuantity = item.quantity + change;

      if (newQuantity < 1) {
        return;
      }

      if (newQuantity > item.stock_quantity) {
        alert(`库存不足，该商品仅剩${item.stock_quantity}件`);
        return;
      }

      item.quantity = newQuantity;
    },
    removeItem(item) {
      this.cartItems = this.cartItems.filter((i) => i.product_id !== item.product_id);
      this.updateSelectAll();
    },
    checkout() {
      const selectedItems = this.cartItems.filter((item) => item.selected);
      if (selectedItems.length === 0) {
        alert("请至少选择一件商品");
        return;
      }
      alert(`订单提交成功！共${this.selectedQuantity}件商品，总金额：${this.selectedTotalPrice.toFixed(2)}元`);
    },
  },
};
</script>

<style scoped>
@import url("./style.css");

/* 顶部导航栏样式 */

.top-nav {
  width: 100%;
  background-color: #f4efd2;
  color: black;
  padding: 15px 0;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: #bdbbb7 0px 0px 5px;
}

.nav-container {
  width: 90%;
  margin: 0 auto;
  display: flex;
  align-items: center;
}

.logo {
  margin-right: 40px;
  height: 40px;
}

img {
  height: 100%;
}

.nav-item {
  width: 60%;
  height: 24px;
  text-align: center;
  padding: 8px 40px;
  margin-right: 15px;
  cursor: pointer;
  font-size: 16px;
  border-radius: 18px;
  transition: all 0.3s;
}

.nav-item:hover {
  background-color: rgba(0, 0, 0, 0.2);
}

.nav-item.active {
  background-color: #d9c596;
  font-weight: bold;
  height: auto;
}

.call {
  background-color: #f9f7e8;
  height: 14px;
  padding: 8px;
  min-width: 1200px; /* 保持客服栏不换行 */
}

a {
  text-decoration: none;
  color: black;
}
.call-item {
  float: right;
}

.call-img {
  height: 18px;
}

/* 空购物车样式 */
.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.empty-cart-icon {
  margin-bottom: 20px;
}

.empty-cart-title {
  font-size: 24px;
  color: #666;
  margin-bottom: 10px;
}

.empty-cart-desc {
  font-size: 16px;
  color: #999;
  margin-bottom: 30px;
}

.empty-cart-button {
  padding: 12px 40px;
  background-color: #e53935;
  color: white;
  border-radius: 4px;
  font-size: 16px;
  transition: background-color 0.3s;
}

.empty-cart-button:hover {
  background-color: #c62828;
}
</style>
